package com.zetatech.bdp.core;

import com.zetatech.bdp.core.resource.FtpLoader;
import com.zetatech.bdp.core.resource.RuleLoader;
import com.zetatech.bdp.core.task.ParseTask;
import com.zetatech.bdp.core.utils.ConfigurationManager;
import com.zetatech.bdp.entity.FtpDFile;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.regex.Pattern;

/**
 * @author cheng.cao@zetatech.com.cn
 */
@Slf4j
public class Bootstrap {

    public static void main(String[] args) throws Exception {
        String DEVICE_LOG_HOME = System.getProperty("DEVICE_LOG_HOME");
        if (DEVICE_LOG_HOME == null || DEVICE_LOG_HOME.trim().isEmpty()) {
            log.error("环境变量{}未设置", "DEVICE_LOG_HOME");
        }
        FutureTask<Integer> ruleLoaderFuture = new FutureTask<>(() -> RuleLoader.load());
        FutureTask<List<FtpDFile>> dFileLoaderFuture = new FutureTask<>(() -> FtpLoader.load());

        new Thread(ruleLoaderFuture, "thread-load-rules").start();
        new Thread(dFileLoaderFuture, "thread-download-file").start();

        if (ruleLoaderFuture.get() == 0) {
            log.error("由于未成功加载到任何规则文件，故直接退出系统");
            return;
        }
        List<FtpDFile> ftpDFiles = dFileLoaderFuture.get();
        if (ftpDFiles.isEmpty()) {
            log.error("由于未成功下载到任何日志文件，故直接退出系统");
            return;
        }
        int parseThreadCoreNum = (int) (Math.ceil(Runtime.getRuntime().availableProcessors() * 0.7));
        if (ftpDFiles.size() < parseThreadCoreNum) {
            parseThreadCoreNum = ftpDFiles.size();
        }
        ExecutorService processPool = Executors.newFixedThreadPool(parseThreadCoreNum);
        String dirPattern = ConfigurationManager.me().getString("ftp.dir-pattern");
        Pattern p = Pattern.compile(dirPattern);

        CompletionService<List<Map<String, String>>> exec = new ExecutorCompletionService<>(processPool);
        for (FtpDFile ftpDFile : ftpDFiles) {
            ParseTask parseTask = new ParseTask(p, ftpDFile);
            exec.submit(parseTask);
        }
        for (int i = 0; i < ftpDFiles.size(); i++) {
            try {
                List<Map<String, String>> result = exec.take().get();
            } catch (Exception e) {
                log.error("get data error", e);
            }
        }
        processPool.shutdown();
    }
}
